<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                    title="添加商品信息"
                    type="success"
                    center
                    show-icon
                    :closable="false"
            >
            </el-alert>
            <!--步骤栏-->
            <el-steps :active="activeIndex-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!--标签导航 name里面的val 会自动绑定到activeIndex上-->
            <el-form status-icon :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsForm"
                     label-position="top">
                <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave"
                         @tab-click="tabClicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input clearable v-model="addGoodsForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input type="number" clearable v-model="addGoodsForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input type="number" clearable v-model="addGoodsForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input type="number" clearable v-model="addGoodsForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                    v-model="addGoodsForm.goods_cat"
                                    :options="cateList"
                                    :props="catProps"
                                    :clearable="true"
                                    @change="handleChange"
                            ></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="(item,index) in manyTabData" :key="index">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border v-for="(attr_name,index) in item.attr_vals" :label="attr_name"
                                             :key="index"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="(item,index) in onlyTabData" :key="index">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-input :value="item.attr_vals"></el-input>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!--action : 图片上传的地址-->
                        <el-upload
                                class="upload-demo"
                                :action="uploadURL"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                list-type="picture"
                                :headers="token"
                                :on-success="handleSuccess"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!--富文本编辑器-->
                        <quill-editor v-model="addGoodsForm.goods_introduce"

                        >

                        </quill-editor>
                        <el-button type="primary" style="display: flex;margin-top: 20px;margin-left: 40%"
                                   @click="addGoods"
                        >添加商品
                        </el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <el-dialog title="图片预览" :visible.sync="previewVisible" width="30%" center>
            <img :src="previewPath" class="previewImg">
        </el-dialog>
    </div>
</template>

<script>
    import _lodash from 'lodash'
    import $axios from '../../network/request'

    export default {
        name: "Add",
        data() {
            return {
                activeIndex: '0',
                addGoodsForm: {
                    goods_name: '',
                    goods_price: '',
                    goods_weight: '',
                    goods_number: '',
                    goods_cat: [],
                    pics: [],
                    // 商品详情
                    goods_introduce: '',
                    attrs:[],
                },
                addGoodsFormRules: {
                    goods_name: [
                        {required: true, message: '请输入商品名称', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 3 到 15  个字符', trigger: 'blur'}
                    ],
                    goods_price: [
                        {required: true, message: '请输入商品价格', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 1 到 15  个字符', trigger: 'blur'}
                    ],
                    goods_weight: [
                        {required: true, message: '请输入商品重量', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 1 到 15  个字符', trigger: 'blur'}
                    ],
                    goods_number: [
                        {required: true, message: '请输入商品数量', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 1 到 15  个字符', trigger: 'blur'}
                    ],
                    goods_cat: [
                        {required: true, message: '请选择商品分类', trigger: 'change'},
                    ],
                },
                cateList: [],
                catProps: {
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                },
                manyTabData: [],
                onlyTabData: [],
                uploadURL: 'http://rambuild.cn:8888/api/private/v1/upload/',
                previewPath: '',
                previewVisible: false
            }
        },
        methods: {
            //获取商品的分类
            getCateList() {
                $axios({
                    url: 'categories',
                    method: 'get'
                }).then(res => {
                    const {data} = res
                    if (data.meta.status !== 200) {
                        return
                    }
                    this.cateList = data.data
                })
            },
            //级联选择器切换事件
            handleChange() {
                if (this.addGoodsForm.goods_cat.length !== 3) {
                    this.addGoodsForm.goods_cat = []
                    return
                }
            },
            //面板切换的事件
            //newTab，是即将进入的tab-pane
            //oldTab，是即将离开的tab-pane
            beforeTabLeave(newTab, oldTab) {
                if (oldTab === '0' && this.addGoodsForm.goods_cat.length !== 3) {
                    this.$message.error("请选择商品类型")
                    return false
                }
            },
            tabClicked() {
                //如果当前激活的tab是1的话，说明是动态参数面板
                if (this.activeIndex === '1') {
                    $axios({
                        url: `/categories/${this.cateId}/attributes`,
                        params: {
                            sel: 'many'
                        }
                    }).then(res => {
                        const {data} = res
                        if (data.meta.status !== 200) {
                            return this.$message.error("请求商品参数异常")
                        }
                        this.manyTabData = data.data

                        data.data.forEach(item => {
                            item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
                        })

                    })
                } else if (this.activeIndex === '2') {
                    $axios({
                        url: `/categories/${this.cateId}/attributes`,
                        params: {
                            sel: 'only'
                        }
                    }).then(res => {
                        const {data} = res
                        if (data.meta.status !== 200) {
                            return this.$message.error("请求商品参数异常")
                        }
                        this.onlyTabData = data.data

                        console.log(this.onlyTabData)
                    })
                }
            },
            //处理图片预览效果
            handlePreview(file) {
                console.log(file)
                this.previewPath = 'http://rambuild.cn:8888/' + file.response.data.tmp_path;
                this.previewVisible = true
                console.log(this.previewPath)
            },
            //处理移除图片
            handleRemove(file) {
                //1:获取将要删除的图片临时路径
                //2:从pics数组中找到这个图片对应的索引值
                //3:使用splice删除
                const filePath = file.response.data.tmp_path
                const i = this.addGoodsForm.pics.findIndex(item => item.pic === filePath)
                this.addGoodsForm.pics.splice(i, 1)
                console.log(this.addGoodsForm)
            },
            //监听图片上传成功的事件
            handleSuccess(response, file, fileList) {
                console.log(response)
                const picInfo = {
                    pic: response.data.tmp_path
                }
                this.addGoodsForm.pics.push(picInfo)
            },
            addGoods() {
                this.$refs.addGoodsForm.validate(valid => {
                    if (!valid) {
                        return this.$message.error("请输入必要的表单项")
                    }
                    // lodash cloneDeep(obj) 复制一个对象

                    const form = _lodash.cloneDeep(this.addGoodsForm);
                    form.goods_cat = this.addGoodsForm.goods_cat.join(',');
                    //出力动态参数
                    this.manyTabData.forEach(x =>{
                        const newInfo={
                            attr_id:x.attr_id,
                            attr_value:x.attr_vals.join(" ")
                        };
                        this.addGoodsForm.attrs.push(newInfo)
                    })
                    //处理静态数属性
                    this.onlyTabData.forEach(x=>{
                        const newInfo={
                            attr_id:x.attr_id,
                            attr_value:x.attr_vals
                        };
                        this.addGoodsForm.attrs.push(newInfo)
                    })
                    form.attrs = this.addGoodsForm.attrs
                    console.log(form);
                    $axios({
                        method: 'post',
                        url:'goods',
                        data:form
                    }).then(res=>{
                        const {data} = res
                        if (data.meta.status!=201){
                            return this.$message.error("添加商品失败")
                        }
                        this.$message.success("添加成功")
                        this.$router.push({
                            path:'/goods'
                        })
                    })

                })
            }

        },
        created() {
            this.getCateList()
        },
        computed: {
            cateId: {
                get() {
                    if (this.addGoodsForm.goods_cat.length === 3) {
                        return this.addGoodsForm.goods_cat[this.addGoodsForm.goods_cat.length - 1]
                    }
                    return null
                }
            },
            token() {
                return {
                    Authorization: sessionStorage.getItem("token")
                }
            }
        },
    }
</script>

<style scoped>
    .previewImg {
        width: 100%;
    }
</style>
